<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select v-model="listQuery.user_status" style="width: 150px" class="filter-item" @change="handleFilter">
        <el-option key="-1" label="全部状态" :value="-1" />
        <el-option key="0" label="已停用" :value="0" />
        <el-option key="1" label="已启用" :value="1" />
      </el-select>
      <el-input v-model="listQuery.qudao" placeholder="请输入cnzz站长账号进行搜索" style="width: 220px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button v-waves class="filter-item btn" type="primary" icon="el-icon-refresh" @click="handleCancel">
        重置
      </el-button>
      <el-button v-waves class="filter-item btn" type="success" icon="el-icon-plus" @click="handleCreate">
        新增cnzz站长
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="序号" align="center" width="60" type="index" />
      <el-table-column label="cnzz站长账户" min-width="110" align="center">
        <template slot-scope="{row}">
          <span>{{ row.qudao }}</span>
        </template>
      </el-table-column>
      <el-table-column label="归属代理" min-width="110" align="center">
        <template slot-scope="{row}">
          <span>{{ row.daili }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单价" min-width="110" align="center">
        <template slot-scope="{row}">
          <span>{{ row.price }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" min-width="120" align="center">
        <template slot-scope="{row}">
          <span>{{ row.remarks ? row.remarks:'-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="配制" align="center" min-width="300" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="success" @click="handleLink(row)">
            获取对接代码
          </el-button>
          <el-button type="primary" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-if="row.status === 1" type="danger" @click="handleStop(row)">
            停用站长
          </el-button>
          <el-button v-if="row.status === 0" type="primary" @click="handleOpen(row)">
            启用站长
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" class="pageShow" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    <pagination v-show="total > 0" layout="prev, pager, next" :small="true" class="pageHidden" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :width="dialogWidth">
      <el-form ref="dataForm" :model="temp" label-position="left" label-width="100px" class="fullwidth">
        <el-form-item label="站长账号">
          <el-input v-model="temp.qudao" placeholder="请输入cnzz站长账号" :disabled="dialogStatus==='update'" />
        </el-form-item>
        <el-form-item label="归属代理">
          <el-select v-model="temp.daili" style="width: 100%" filterable class="filter-item" :disabled="dialogStatus==='update'">
            <el-option v-for="(value) in dailiArr" :key="value" :label="value" :value="value" />
          </el-select>
        </el-form-item>
        <el-form-item label="单价" style="letter-spacing: 27px;">
          <el-input v-model="temp.price" placeholder="请输入单价" />
        </el-form-item>
        <el-form-item label="统计代码">
          <el-input v-model="temp.counts" type="textarea" :autosize="{ minRows: 4, maxRows: 8}" resize="none" placeholder="请输入统计代码" />
        </el-form-item>
        <el-form-item label="web_id" style="letter-spacing: 1px;">
          <el-input v-model="temp.web_id" placeholder="请输入统计代码的web_id参数" />
        </el-form-item>
        <el-form-item label="备注" style="letter-spacing: 27px;">
          <el-input v-model="temp.remarks" placeholder="请输入备注" />
        </el-form-item>
        <div style="text-align: right">
          <el-button @click="dialogFormVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
            确定
          </el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, create, update, fetchDaili, stopQudao, openQudao } from '@/api/cnzz/cnzzqudao'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { MessageBox, Message } from 'element-ui'

export default {
  name: 'Cnzzqudao',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        qudao: '',
        user_status: 1
      },
      dailiArr: [],
      temp: {
        id: undefined,
        web_id: '',
        qudao: '',
        daili: '',
        counts: '',
        price: '',
        remarks: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      dialogWidth: 0,
      textMap: {
        update: '修改cnzz站长',
        create: '新增cnzz站长'
      },
      rules: {
        user_login: [
          { required: true, message: '账号是必需的', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (/^[a-zA-Z0-9]+$/.test(value) === false) {
                callback(new Error('账号只能包含英文和数字'))
              } else {
                callback()
              }
            }, trigger: 'blur'
          }
        ],
        user_pass: [{ required: true, message: '密码是必需的', trigger: 'blur' }],
        price: [
          { required: true, message: '单价是必需的', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (/^[1-9][0-9]*(\.[0-9]{1,2})?$/.test(value) === false) {
                callback(new Error('请输入一个数字，只支持两位小数'))
              } else {
                callback()
              }
            }, trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getDailiArr()
    this.setDialogWidth()
  },
  mounted() {
    window.onresize = () => {
      return (() => {
        this.setDialogWidth()
      })()
    }
  },
  methods: {
    setDialogWidth() {
      const val = document.body.clientWidth
      const def = 550 // 默认宽度
      if (val < def) {
        this.dialogWidth = '100%'
      } else {
        this.dialogWidth = def + 'px'
      }
    },
    getDailiArr() {
      fetchDaili().then(response => {
        if (response.code === 1) {
          this.dailiArr = response.data
        } else {
          Message({
            message: response.msg || '获取数据失败',
            type: 'error',
            duration: 2000
          })
        }
      })
    },
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data
        this.total = response.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleCancel() {
      this.listQuery.page = 1
      this.listQuery.qudao = ''
      this.listQuery.user_status = 1
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        web_id: '',
        qudao: '',
        daili: '',
        counts: '',
        price: '',
        remarks: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    createData() {
      if (this.temp.qudao === '') {
        Message({
          message: '请填写cnzz站长账号',
          type: 'error',
          duration: 2000
        })
        return
      }
      if (this.temp.daili === '') {
        Message({
          message: '请选择归属代理',
          type: 'error',
          duration: 2000
        })
        return
      }
      if (this.temp.price === '') {
        Message({
          message: '请填写单价',
          type: 'error',
          duration: 2000
        })
        return
      }
      if (/^[1-9][0-9]*(\.[0-9]{1,2})?$/.test(this.temp.price) === false) {
        Message({
          message: '单价只能是数字，且只支持两位小数',
          type: 'error',
          duration: 2000
        })
        return
      }
      if (!this.temp.counts && this.temp.web_id) {
        Message({
          message: '请填写统计代码',
          type: 'error',
          duration: 2000
        })
        return
      }
      if (this.temp.counts && !this.temp.web_id) {
        Message({
          message: '请填写web_id',
          type: 'error',
          duration: 2000
        })
        return
      }
      create(this.temp).then(response => {
        if (response.code === 1) {
          this.handleFilter()
          this.dialogFormVisible = false
          Message({
            message: response.msg || '添加成功',
            type: 'success',
            duration: 2000
          })
        } else {
          Message({
            message: response.msg || '添加失败',
            type: 'error',
            duration: 2000
          })
        }
      })
    },
    handleLink(row) {
      this.$router.push({
        path: '/cnzz/javascript/' + row.qudao
      })
    },
    handleUpdate(row) {
      this.temp.id = row.id
      this.temp.qudao = row.qudao
      this.temp.daili = row.daili
      this.temp.price = row.price
      this.temp.counts = row.counts
      this.temp.remarks = row.remarks
      this.temp.web_id = row.web_id
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
    },
    updateData() {
      if (this.temp.qudao === '') {
        Message({
          message: '请填写cnzz站长账号',
          type: 'error',
          duration: 2000
        })
        return
      }
      if (this.temp.price === '') {
        Message({
          message: '请填写单价',
          type: 'error',
          duration: 2000
        })
        return
      }
      if (/^[1-9][0-9]*(\.[0-9]{1,2})?$/.test(this.temp.price) === false) {
        Message({
          message: '单价只能是数字，且只支持两位小数',
          type: 'error',
          duration: 2000
        })
        return
      }
      if (!this.temp.counts && this.temp.web_id) {
        Message({
          message: '请填写统计代码',
          type: 'error',
          duration: 2000
        })
        return
      }
      if (this.temp.counts && !this.temp.web_id) {
        Message({
          message: '请填写web_id',
          type: 'error',
          duration: 2000
        })
        return
      }
      update(this.temp).then(response => {
        if (response.code === 1) {
          this.dialogFormVisible = false
          this.getList()
          Message({
            message: response.msg || '修改成功',
            type: 'success',
            duration: 2000
          })
        } else {
          Message({
            message: response.msg || '修改失败',
            type: 'error',
            duration: 2000
          })
        }
      })
    },
    handleStop(row) {
      MessageBox.confirm('确定将站长号为 ' + row.qudao + ' 的站长停用吗', '确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        const data = {
          qudao: row.qudao
        }
        stopQudao(data).then(response => {
          loading.close()
          if (response.code === 1) {
            if (this.list.length === 1 && this.listQuery.user_status === 1) {
              this.handleFilter()
            } else {
              this.getList()
            }
            Message({
              message: response.msg || '停用成功',
              type: 'success',
              duration: 2000
            })
          } else {
            Message({
              message: response.msg || '停用失败',
              type: 'error',
              duration: 2000
            })
          }
        })
      }).catch(() => {})
    },
    handleOpen(row) {
      MessageBox.confirm('确定将站长号为 ' + row.qudao + ' 的站长开启吗', '确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        const data = {
          qudao: row.qudao
        }
        openQudao(data).then(response => {
          loading.close()
          if (response.code === 1) {
            if (this.list.length === 1 && this.listQuery.user_status === 0) {
              this.handleFilter()
            } else {
              this.getList()
            }
            Message({
              message: response.msg || '启用成功',
              type: 'success',
              duration: 2000
            })
          } else {
            Message({
              message: response.msg || '启用失败',
              type: 'error',
              duration: 2000
            })
          }
        })
      }).catch(() => {})
    }
  }
}
</script>

<style lang="scss" scoped>
  .show-pwd {
    position: absolute;
    right: 10px;
    top: 0;
    font-size: 16px;
    color: #ccc;
    cursor: pointer;
    user-select: none;
  }
  .pageHidden{
    display: none;
  }
  .btn{
    margin-left:0;
  }
  .fullwidth{
    width: 400px;
    margin-left:50px;
  }
  @media (max-width:550px) {
    .pageShow {
      display: none;
    }
    .pageHidden {
      display: block;
    }
    .fullwidth{
      width:100%;
      margin-left:0;
    }
  }
</style>
